package com.theexceptions.todo.view;

import java.util.Calendar;
import java.util.GregorianCalendar;

import com.theexceptions.todo.controller.AddTaskController;
import com.theexceptions.todo.model.Location;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

/**
 * An Activity that manages adding tasks. Corresponds to the view: addtask.xml.
 * 
 * @author TheExceptions
 */
public class AddTaskActivity extends Activity {

	public static Button locationButton = null;

	private Button pickDate;
	private int dispYear;
	private int dispMonth;
	private int dispDay;

	private TextView mTimeDisplay;
	private Button mPickTime;

	private int mHour;
	private int mMinute;

	static final int TIME_DIALOG_ID = 0;

	static final int DATE_DIALOG_ID = 1;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Set context view to addtask.xml
		setContentView(R.layout.addtask);

		// Reset location object
		AddTaskController.resetLocation();

		locationButton = ((Button) findViewById(R.id.selectLocation));

		// Add a listener to the pickDate button
		pickDate = (Button) findViewById(R.id.pickDate);
		pickDate.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(DATE_DIALOG_ID);
			}
		});

		// Get the current date
		final Calendar c = Calendar.getInstance();
		dispYear = c.get(Calendar.YEAR);
		dispMonth = c.get(Calendar.MONTH);
		dispDay = c.get(Calendar.DAY_OF_MONTH);
		updateDisplay();

		// "Repeat" Spinner
		Spinner repeatSpinner = (Spinner) findViewById(R.id.repeatSpinner);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.repeat_array, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		repeatSpinner.setAdapter(adapter);

		repeatSpinner.setOnItemSelectedListener(new MyOnItemSelectedListener());

		// "Reminder" Spinner
		Spinner reminderSpinner = (Spinner) findViewById(R.id.reminderSpinner);
		ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(
				this, R.array.reminder_array, android.R.layout.simple_spinner_item);
		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		reminderSpinner.setAdapter(adapter2);

		reminderSpinner.setOnItemSelectedListener(new MyOnItemSelectedListener());

		// "Category" Spinner
		Spinner categorySpinner = (Spinner) findViewById(R.id.categorySpinner);
		ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource(
				this, R.array.category_array, android.R.layout.simple_spinner_item);
		adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		categorySpinner.setAdapter(adapter3);

		categorySpinner.setOnItemSelectedListener(new MyOnItemSelectedListener());

		// ADDS TIME?
		// capture our View elements
		mTimeDisplay = (TextView) findViewById(R.id.timeDisplay);
		mPickTime = (Button) findViewById(R.id.pickTime);

		// add a click listener to the button
		mPickTime.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(TIME_DIALOG_ID);
			}
		});

		// get the current time
		mHour = c.get(Calendar.HOUR_OF_DAY);
		mMinute = c.get(Calendar.MINUTE);

		// display the current date
		updateTimeDisplay();
	}

	/**
	 * Listener for the save task button.
	 * 
	 * @param view
	 */
	public void saveTaskButtonClicked(View view) {
		/*
		 * JUnit tested: success
		 */

		String name = ((EditText) findViewById(R.id.editText1)).getText().toString();
		Calendar time = new GregorianCalendar(dispYear, dispMonth + 1, dispDay);

		Spinner categorySpinner = (Spinner) findViewById(R.id.categorySpinner);
		String category = (String) categorySpinner.getSelectedItem();

		String desc = ((EditText) findViewById(R.id.editText2)).getText().toString();

		if (name == null || name.equals("")) {
			Toast.makeText(this, "Please fill in name!", Toast.LENGTH_SHORT).show();
			return;
		}

		// TODO retrieve valid repeat, reminder
		int result = AddTaskController.addTask(name, time, null, null, category.equals("None") ? null
				: category, desc);

		if (result == AddTaskController.ADD_TASK_SUCCESS) {
			Toast.makeText(this, "Task added sucessfully!", Toast.LENGTH_SHORT).show();
			setResult(Activity.RESULT_OK);
			finish();
		} else if (result == AddTaskController.ADD_TASK_ERROR) {
			Toast.makeText(this, "An unknown error occurred.", Toast.LENGTH_SHORT).show();
		}
	}

	public void cancelAddTaskButtonClicked(View view) {
		setResult(Activity.RESULT_CANCELED);
		finish();
	}

	public void selectLocationButtonClicked(View view) {
		Intent intent = new Intent(view.getContext(), SearchMapActivity.class);
		startActivityForResult(intent, 1000);
	}

	public class MyOnItemSelectedListener implements OnItemSelectedListener {

		public void onItemSelected(AdapterView<?> parent,
				View view, int pos, long id) {
		}

		public void onNothingSelected(AdapterView parent) {
		}
	}

	// updates the date in the TextView
	private void updateDisplay() {
		pickDate.setText(
				new StringBuilder()
						// Month is 0 based, add 1
						.append(dispMonth + 1).append("-")
						.append(dispDay).append("-")
						.append(dispYear).append(" "));
	}

	// the callback received when the user "sets" the date in the dialog
	private DatePickerDialog.OnDateSetListener mDateSetListener =
			new DatePickerDialog.OnDateSetListener() {

				public void onDateSet(DatePicker view, int year,
						int monthOfYear, int dayOfMonth) {
					dispYear = year;
					dispMonth = monthOfYear;
					dispDay = dayOfMonth;
					updateDisplay();
				}

			};

	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this,
					mDateSetListener,
					dispYear, dispMonth, dispDay);

		case TIME_DIALOG_ID:
			return new TimePickerDialog(this,
					mTimeSetListener, mHour, mMinute, false);
		}
		return null;
	}

	private void updateTimeDisplay() {
		mPickTime.setText(
				new StringBuilder()
						.append(pad(mHour)).append(":")
						.append(pad(mMinute)));
	}

	private static String pad(int c) {
		if (c >= 10)
			return String.valueOf(c);
		else
			return "0" + String.valueOf(c);
	}

	// the callback received when the user "sets" the time in the dialog
	private TimePickerDialog.OnTimeSetListener mTimeSetListener =
			new TimePickerDialog.OnTimeSetListener() {
				public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
					mHour = hourOfDay;
					mMinute = minute;
					updateTimeDisplay();
				}
			};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// Set text of location button to name of location
		if (requestCode == 1000) {
			if (resultCode == 1000) {
				Location loc = AddTaskController.getLocation();
				String name = loc.getName();

				if (name.length() > 30)
					name = name.substring(0, 27) + "...";

				if (loc != null)
					locationButton.setText(name);
			}
		}
	}

}